const http=require('http');
const fs=require('fs');
const url=require('url');
const uuidv4 = require('uuid/v4');

let server=http.createServer((req,res)=>{
    let {pathname,query}=url.parse(req.url,true);
    console.log(pathname)
    if(pathname=='/upload'){
        //接口地址
        //3.接收字符串
        let str='';
        req.on('data',data=>{
            str+=data;
        })
        req.on('end',()=>{
            str=decodeURIComponent(str);
            str=str.replace(/data:[a-z\-]+(\/[a-z\-]+)?;base64,/i,'')

            // //4.保存下来
            fs.writeFile(`./www/upload/${uuidv4().replace(/\-/g,'')}`,str,'base64',err=>{
                if(err){
                    console.log(1)
                    // res.write('上传错误')
                }else{
                    console.log(1)
                    res.write('404')
                }
                res.end();
                
            })
        })
    }else{
        fs.readFile(`10.canvas.html`,(err,data)=>{
            if(err){
                res.writeHead(404);
                res.write('404')
            }else{
                res.write(data)
            }
            res.end()
        })
    }
})
server.listen(8080);